import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/order_list_entity.dart';
import '../../utils/constant.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:nim_core/nim_core.dart';
import '../../widgets/simple_dialog.dart';
import '../msg/group.dart';
import '../sell/sell.dart';
import 'orderDetail.dart';
import 'package:bot_toast/bot_toast.dart';

class OrderSellController extends GetxController{
  @override
  void onInit() {
    super.onInit();
    clickTabIndex = Get.arguments;
    _getService();
  }
  @override
  void onClose() {
    super.onClose();
    BotToast.closeAllLoading();
  }
  int clickTabIndex = 0;
  List<Map> tabs=[{'name':'全部','value':''},{'name':'审核中','value':'0'},
    // {'name':'交易中','value':'12'},
    {'name':'已上架','value':'1'},{'name':'交易中','value':'11'}
    ,{'name':'已成交','value':'15'},{'name':'审核失败','value':'23'}];
  List<OrderListData> list = [];
  List<OrderListData> allList = [];
  void _getService(){
    DioManager.getInstance().post(ServiceUrl.myGoodsList,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      OrderListEntity bannerEntity = OrderListEntity.fromJson(jsonDecode(data));
      allList = bannerEntity.data;
      _filteData();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  _filteData(){
    if(clickTabIndex == 0){
      list = allList;
    }else{
      list= [];
      for(var item in allList){
        if(clickTabIndex == 1){
          if(item.status == 0){
            list.add(item);
          }
        }
        else if(clickTabIndex == 2){
          if(item.status == 1){
            list.add(item);
          }
        }
        else if(clickTabIndex == 3){
          if(item.status == 11 || item.status == 12 ||item.status == 13 ){
            list.add(item);
          }
        }
        else if(clickTabIndex == 5){
          if(item.status == 23 ){
            list.add(item);
          }
        }
        else{
          if(item.status ==15){
            list.add(item);
          }

        }
      }
    }
  }

  void _cancelOrder(context ,cid,oid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.cancelGoods,{
            "channel_id":cid.toString(),
            "goods_id":oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });

        }
      },
        msg: "是否撤销商品审核？撤销后该商品不再展示",
        sureText: "确定",
      );
    });

  }
  void _off(context,cid,gid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.offGoods,{
            "channel_id":cid.toString(),
            "goods_id":gid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });

        }
      },
        msg: "是否下架商品？下架后该商品不再展示",
        sureText: "确定",
      );
    });


  }
  void _refresh(channel_id,goods_id){
    DioManager.getInstance().post(ServiceUrl.refreshGoods,{
      "user_name":UserUtil.getUSER()?.userName.toString(),
      "channel_id":channel_id.toString(),
      "goods_id":goods_id.toString()
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      _getService();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _sureOrder(context,cid,oid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.sureOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "order_id": oid.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否确认该订单？",
        sureText: "确定",
      );
    });
  }

  void _buyNow(context,cid,gid){
    showDialog(context: context, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.sureOrder,{
            "user_name": UserUtil.getUSER()?.userName,
            "channel_id": cid.toString(),
            "goods_id": gid.toString(),
            "buy_type":3
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getService();
            update();
          }, (error) {
            ToastUtil.show(error);
          });
        }
      },
        msg: "是否立即支付该订单？",
        sureText: "确定",
      );
    });
  }

  _queryTeam(teamId) async {

    NIMResult<NIMTeam> aa= await NimCore.instance.teamService.queryTeam(teamId);
    if(aa.isSuccess){
      Get.to(() => GroupPage(),
          arguments: {
            'sessionId':teamId,
            'nickName':aa.data!.name,
            'servicePhoto':aa.data!.icon,
            'account':teamId,
          },
          preventDuplicates: false)
         ;
    }

  }
  
  EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: false,
  );
}


class OrdersSellPage extends GetView<OrderSellController>  {
  late OrderSellController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<OrderSellController>(() => OrderSellController());
    controller = Get.find();
    context = context1;

    return GetBuilder<OrderSellController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '我的商品',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }


  Widget _empty(){
    return Container(
      margin: EdgeInsets.only(top: 30.h),
      alignment: Alignment.center,
      child: Image.asset(Constant.IMG_BASE+'empty.png',width: 150.w,height: 127.h,),
    );
  }

  Widget _content(){
    return Container(
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(left:16.w,right: 16.w ,top: 16.h),
            child:   Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: tabsItems(),
            )
          ),
          _line(),
          controller.list.length==0?_empty():
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height - 8.h - 130.h,
            child: _refresh(),
          )
        ],
      ),
    );
  }
  
  Widget _line(){
    return Container(
      width: MediaQuery.of(context).size.width,
      color: Color(0xFFF7F8FC),
      height: 8.h,
    );
  }
  


  List<Widget> tabsItems(){
    List<Widget> aa = [];
    for(int i =0 ;i<controller.tabs.length;i++){
      aa.add(_tabItem(controller.tabs[i]['name'],i));
    }
    return aa;
  }

  Widget _tabItem(name,index){
    return InkWell(
      onTap: (){
        controller.clickTabIndex = index;
        controller._filteData();
        controller.update();
      },
      child: Column(
        children: [
          Text(name,style: TextStyle(color:Color(0xFF333333),fontSize: 14.sp),),
          SizedBox(height: 10.h,),
          index == controller.clickTabIndex?
          Container(
            width: 27.w,
            height: 2.h,
            color: Color(0xFF007BE5),
          ):Container(height: 2.h,)
        ],
      )
    ) ;
  }

  Widget _refresh(){
    return   Scaffold(
        backgroundColor: Colors.white,
        body:  EasyRefresh(
          header: ClassicHeader(
            dragText: 'Pull to refresh'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Refreshing...'.tr,
            processingText: 'Refreshing...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          footer: ClassicFooter(
            dragText: 'Pull to load'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Loading...'.tr,
            processingText: 'Loading...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          controller: controller.easyRefreshController,
          onRefresh: () async {
            controller._getService();
          },
          onLoad: () async {
            // controller.easyRefreshController.finishLoad(
            //     IndicatorResult.noMore );
          },
          child: ListView.separated(
            itemBuilder: (context, index) {
              return _gameItems(controller.list[index]);
            }, separatorBuilder: (BuildContext context, int index) {
              return Container(height: 8.h,color: Color(0xFFF7F8FC),);
          }, itemCount: controller.list.length,
          ),
        ));
  }

  Widget _gameItems(OrderListData item){
    return
      InkWell(
          onTap: (){
            print('statusstatusstatusstatus'+item.status.toString());
            if(item.status == 0 || item.status == 1 || item.status == 11 || item.status == 12 || item.status == 13 ||item.status ==23||item.status ==21){
            Get.to(()=>SellPage(),arguments: {
            'goods_id':item.id.toString(),
            'status':item.status.toString(),
            'channel_id':item.channelId.toString(),
            'channel_name':'',
            'title':item.categoryText,
            },preventDuplicates:false);
            }else{
            Get.to(()=>OrderDetailPage(),arguments: {
            'channel_id':item.channelId.toString(),
            'order_id':item.id.toString()
            },preventDuplicates:false)?.then((value) => {
            controller._getService()
            });
            }

            // if(controller.clickTabIndex == 1){
            //   if(item.status == 0 ){
            //     list.add(item);
            //   }
            // }
            // else if(clickTabIndex == 2){
            //   if(item.status == 1){
            //     list.add(item);
            //   }
            // }
            // else if(clickTabIndex == 3){
            //   if(item.status == 11 || item.status == 12 ||item.status == 13 ){
            //     list.add(item);
            //   }
            // }
            // else if(clickTabIndex == 5){
            //   if(item.status == 23 ){
            //     list.add(item);
            //   }
            // }
            // else{
            //   if(item.status ==15){
            //     list.add(item);
            //   }
            //
            // }

          },
          child: Container(
            margin: EdgeInsets.only(left: 16.w,right: 13.w,top: 24.h),
            child:
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('订单号：${item.id}',style: TextStyle(
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.bold,
                      fontSize: 12.sp
                    ),),
                    InkWell(
                      onTap: (){
                        if(item.status==23){
                          showDialog(context: context, builder: (BuildContext context1) {
                            return MySimpleDialog(callBack: (String content) {
                              if(content == 'cancel'){
                                Navigator.pop(context1);
                              }else if(content == 'sure'){
                                Navigator.pop(context1);
                              }
                            },
                              msg: item.roleText,
                              sureText: "确定",
                            );
                          });
                        }
                      },
                      child:  Text(Common.sellOrderStatusToText(item.status),style: TextStyle(
                          color: Color(0xFF007BE5),
                          fontSize: 12.sp
                      ),)
                    )
                   ,
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 13.h,bottom: 13.h),
                  color: Color(0xFFF3F3F3),
                  height: 1.h,
                ),
                Row(
                  children: [
                    Container(
                        width: 100.w,
                        height: 78.h,
                        child: Stack(
                          children: [

                            ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                              child:  Image.network(Common.realPicPath(item.imgUrl),width: 100.w,height: 78.h,fit: BoxFit.cover,)
                            ),
                            item.isBaopei == 1?
                            _officer():Container(),
                          ],
                        )

                    ),
                    SizedBox(width: 14.w,),
                    Container(
                        width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w,
                        child:  Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(item.title,
                              style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),maxLines: 2,    textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,),
                            SizedBox(height: 10.h,),
                            Text('区服：${item.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                            SizedBox(height: 6.h,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    _second(item.isMsg),
                                    _fenqi(item.isBystages)
                                  ],
                                ),
                                Row(
                                  children: [
                                    Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                                    Text(item.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                                  ],
                                )

                              ],
                            )
                          ],
                        )
                    )
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 13.h,bottom: 13.h),
                  color: Color(0xFFF3F3F3),
                  height: 1.h,
                ),

                _btns(item),
                SizedBox(height: 11.h,)
              ],
            )
           ,
          )
      )
    ;
  }
  
  Widget _second(msg1){
    String msg = '不包人脸';
    if(msg1==1){
      msg = '可二次';
    }
    if(msg1==2){
      msg = '可包人脸';
    }
    return Container(
      width: 55.w,
      height: 20.h,
      margin: EdgeInsets.only(right: 5.w),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(14.r),
        border: Border.all(width: 1.w,color: Color(0xFF4EBCFF))
      ),
      child: Text(msg,style: TextStyle(
        color: Color(0xFF4EBCFF),
        fontSize: 12.sp
      ),),
    );
  }

  Widget _fenqi(msg1){
    String msg = '不可分期';
    if(msg1==1){
      msg = '可分期';
    }
    return Container(
      width: 55.w,
      height: 20.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(14.r),
          border: Border.all(width: 1.w,color: Color(0xFF4EBCFF))
      ),
      child: Text(msg,style: TextStyle(
          color: Color(0xFF4EBCFF),
          fontSize: 12.sp
      ),),
    );
  }
  
  Widget _btns(OrderListData item){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(Common.transferDate(item.traTime),style: TextStyle(
          color: const Color(0xFF999999),
          fontSize: 12.sp
        ),)  ,
        (item.status==23||item.status==22)?Text('原因：'+item.roleText,style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),):
        Row(
          children: [
            item.status==0?
            _btn('修改信息',item):Container(),
            item.status==0?
            _btn('撤销审核',item):Container(),

            item.status==1?
            _btn('刷新置顶',item):Container(),
            item.status==1?
            _btn('下架商品',item):Container(),

            item.status==11|| item.status==12||item.status==13?
            _btn('进入交易群组',item):Container(),
          ],
        )
      ],
    );
  }
  
  Widget _btn(name,OrderListData item){
    return InkWell(
      onTap: (){
        if(name=='修改信息'){
          Get.to(()=>SellPage(),arguments: {
            'goods_id':item.id.toString(),
            'status':item.status.toString(),
            'channel_id':item.channelId.toString(),
            'channel_name':'',
            'title':item.categoryText,
          },preventDuplicates:false);
        }else if(name=='刷新置顶'){
          controller._refresh(item.channelId, item.id);
        }
        else if(name=='撤销审核'){
          controller._cancelOrder(context,item.channelId, item.id);
        }else if(name=='立即支付'){
          controller._buyNow(context,item.channelId,item.id);
        }else if(name=='确认收货'){
          controller._sureOrder(context,item.channelId,item.id);
        }else if(name=='进入交易群组'){
          controller._queryTeam(item.teamId);
        }else if(name=='下架商品'){
          controller._off(context,item.channelId,item.id);
        }
        
      },
      child:  Container(
        width: 80.w,
        height: 28.h,
        margin: EdgeInsets.only(right: 3.w),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(17.r),
            border: Border.all(width: 1.w,color: Color(0xFFC7C7C7))
        ),
        child: Text(name,style: TextStyle(
            color: const Color(0xFFC7C7C7),
            fontSize: 12.sp
        ),),
      )
    );
  }

  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }

}